package com.demo.common.utils;

import com.demo.common.exceptions.ServiceException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 公共校验类
 */
public class ValidatorUtils {

    private static final Validator validator= Validation.buildDefaultValidatorFactory().getValidator();;

    /**
     * 校验对象
     *
     * @param object 待校验对象
     * @param groups 待校验的组
     */
    public static void validate(Object object, Class<?>... groups)
            {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            String msg = constraintViolations.stream().map(ConstraintViolation::getMessage).collect(Collectors.joining("；"));
            throw new ServiceException(msg);
        }
    }

    /**
     * 指定默认 groups
     *
     * @param object 要校验的对象
     */
    public static void validate(Object object) {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, Default.class);
        if (!constraintViolations.isEmpty()) {
            String msg = constraintViolations.stream().map(ConstraintViolation::getMessage).collect(Collectors.joining("；"));
            throw new ServiceException(msg);
        }
    }

}
